require.async(['JqueryBase','base64','UrlUtil','jquery.SuperSlide2'],function(window){
 
var estateId = UrlUtil.getUrlParamBase64("estateId");
var serveStandardId = UrlUtil.getUrlParamBase64("serveStandardId");
var cityName = CookieUtil.get(Constant.CITY_NAME);  
// 预约时间列表
window.listBespeaktime = function(day){

	if(ValidUtil.isBlank(day)){ 
		layer.msg("请选择服务日期"); 
		return ;
	}    
	if(ValidUtil.isBlank(estateId) || ValidUtil.isBlank(serveStandardId)){
		//layer.msg("参数错误");  
		window.history.back(); 
		return ; 
	}
	layer.load(2);//加载中
	BaseUtil.get("eb/bespeakNonTime/listBespeakNonTime",function(result){ 
		layer.closeAll('loading');//关闭加载中
		var objs = result; 
		var html = '<td {function} class="{validclass}"><i></i><span name="timetext">{timetext}</span><span class="selectedbg"></span><input type="hidden" name="time" value="{timevalue}" /></td>';
		var htmlArr = ['<tr><td colspan="5"><span id="currDate">'+day + " [ " +DateUtil.getWeek(day)+' ] </span></td></tr>'];   
		//预约时间 
		var isFrist = true;
		$.each(objs,function(idx,item){//valid  
			if(idx == 0 || idx % 5 == 0){
				htmlArr.push("<tr>");
			}   
			htmlArr.push(html.replaceAll("{validclass}",item.isValid ? "valid"+(isFrist?" current":""):"")
					.replaceAll("{timetext}",item.serveTimeText)
					.replaceAll("{timevalue}",item.serveTimeValue)
					.replaceAll("{function}",item.isValid ? 'onclick="selectTime(this)"  onmouseover="this.style.backgroundColor=\'#f8f8f8\'" onmouseout=\"this.style.backgroundColor=\'\'\" ':''));
			if(idx == objs.length -1){
				htmlArr.push("<td></td><td></td><td></td></tr>");
			} else if((idx+1) / 5 == 1){     
				htmlArr.push("</tr>");
			} 
			if(item.isValid) isFrist = false;//是否头一个可预约时间？ 
		});   
		htmlArr.push('<tr><td colspan="5"></td></tr>'); 
		$("#bespeaktime_tab").html(htmlArr.join(''));
		// 显示 
		selectTime($("#bespeaktime_tab .current")) ;    
	},{"bespeakDay":day,"standardId":serveStandardId,"estateId":estateId});    
}
// 预约信息
window.getServeOrder = function(){
	
	if(ValidUtil.isBlank(CookieUtil.get(Constant.CITY_CODE))) {
		layer.alert("定位城市失败，请刷新后重试"); 
		return;
	}
	if(ValidUtil.isBlank(estateId)||ValidUtil.isBlank(serveStandardId)){
		layer.msg("参数错误");  
		window.history.back();
		return ;
	}
	BaseUtil.get("eb/serve/serveOrderConfirm",function(result){ 
		var objs = result;
		if(cityName != objs.estate.cityName){ //此页面切换城市后退 
			  layer.alert("请注意，您所选的服务小区不在当前定位城市");    
		} 
		$("#serveName").html(objs.serveName + " (" + objs.serviceName + ") ");   
		$("#servicePrice").html(NumberUtil.roundString(objs.servicePrice));  
		//服务共计
		$("#servicePriceSum").html(NumberUtil.roundString(objs.servicePrice));
		//支付金额
		$("#totalPrice").html(NumberUtil.roundString(objs.servicePrice)); 
		//小区信息 
		$("#estateName").html(objs.estate.estateName);//setEstate 
		$("#estateAddress").html(objs.estate.provinceName+objs.estate.cityName+objs.estate.areaName+objs.estate.address);//setEstate
		
		//订单信息
		$("#estateId").val(objs.estate.id);//setEstate 
		$("#serviceTotalPrice").val(objs.servicePrice);   
		$("#serveStandardSnapshotId").val(serveStandardId);    
		//加载洗车卡 and 优惠券
		listWashCard(objs.id,estateId,objs.serviceValue); 
	},{"serveStandardId":serveStandardId,"estateId":estateId});  
}

listBespeaktime(DateUtil.getDate());  
getServeOrder();  
// 选择优惠券
window.selectCoupon = function(val){ 
	var price = 0;
	if(val && val != '' && val.split("_").length > 0){
		price = val.split('_')[1]; 
	}
	if(price == '-1'){
		price = $("#serviceTotalPrice").val();   
	}
	$("#couponprice").html(NumberUtil.roundString(price));     
	$("#totalPrice").html(NumberUtil.roundString(NumberUtil.sub($("#serviceTotalPrice").val(),price)));  
}
// 选择预约时间
window.selectTime = function(obj){    
	$("#bespeaktime_tab").find("td").removeClass("current"); 
	$(obj).addClass("current"); 
	$("#bespeakTime").val($(obj).find("input[name=time]").val());     
	var washtime = $("#currDate").html() + $(obj).find("span[name=timetext]").html();
	$("#washtime").html(washtime ? washtime : "");      
} 
// 提交订单 
window.submitOrder = function(obj){ 
	var bespeakTime = $("#bespeaktime_tab .current").find("input[name=time]").val();          
	var linkman = $("#linkman").val();
	var linkmobile = $("#linkmobile").val();
	var carno = $("#carno").val();
	var remark = $("#remark").val(); 
	var cw = $("#coupon").val();
	var couponId = null,washCardId = null;     
	if(cw && cw != ''){
		var cid = $("#coupon").val().split("_")[0];
		var cprice = $("#coupon").val().split("_")[1];
		if(cprice == '-1'){ 
			washCardId = cid;  
		} else if(NumberUtil.roundString(cprice) > 0){
			couponId = cid;  
		}
	}
	if(ValidUtil.isBlank(bespeakTime)){
		layer.msg("请选择预约时间");
		return;
	}
	if(ValidUtil.isBlank(linkman)){
		layer.msg("请输入联系人");
		return;
	} else if(linkman.length < 2){
		layer.msg("联系人姓名至少2个字符");
		return;
	} 
	if(ValidUtil.isBlank(linkmobile)){
		layer.msg("请输入手机号");
		return;
	} else if(!ValidUtil.isMobile(linkmobile)){
		layer.msg("请输入正确的手机号");
		return;
	} 
	if(carno != '' && !ValidUtil.isVehicleNumber(carno)){
		layer.msg("请输入正确的车牌号");
		return;
	} 
	var estateId = $("#estateId").val();//setEstate 
	var serveStandardId = $("#serveStandardSnapshotId").val();    
	if(ValidUtil.isBlank(estateId)|| ValidUtil.isBlank(serveStandardId)){
		layer.msg("参数错误，请刷新后重试");
		return;
	}  
	var formData = {
		"washCardId":washCardId,   
		"couponId":couponId,   
		"bespeakTime":bespeakTime,
		"estateId":estateId,
		"serveStandardSnapshotId":serveStandardId,
		"remark":remark,
		"car.ownerName":linkman,
		"car.ownerMobile":linkmobile,
		"car.carNo":carno,
		"stopPlace":$("#stopPlace").val()
	} 
	layer.msg('正在为您提交订单', {
		icon: 16
		,shade: 0.01
	}); 
	BaseUtil.post("eb/bespeak/submitBespeak",function(result){ 
		if(result.success){  
			location.href = basePath + '/serve/auth/servicepayfor.html?ordno='+result.data;
		} else {
			layer.alert(result.msg);
			listBespeaktime($('#dateinfo').val());
		}  
	},formData); 
}

// 选中联系人
window.linkManShow = function(id,ownerName,ownerMobile,carNo){ 
	$("#carno").val(carNo);
	$("#linkman").val(ownerName);
	$("#linkmobile").val(ownerMobile);
	 
	$("#linkmanText").html(ownerName);  
	$("#linkmobileText").html(ownerMobile); 
}
// 常用联系人列表 
var linkManHtml = '<tr onclick="checkedRadio(this)" style="height: 30px"  onmouseover="this.style.backgroundColor=\'#f8f8f8\'" onmouseout="this.style.backgroundColor=\'\'" ><td>{radio}</td><td>{name}</td><td>{mobile}</td><td>{car}</td></tr>';
var linkManHtmlArr = [];
function listCar(){
	
	BaseUtil.get("crm/car/webListCar",function(result){

		var result = result.data;
		//联系人
		if(result){  
			linkManShow(result.items[0].id,result.items[0].ownerName,result.items[0].ownerMobile,result.items[0].carNo);
			
			$.each(result.items,function(idx,item){ 
				//linkManHtml += '<br/><label><input type="radio" name="linkman" value="'+item.id+"_"+ item.ownerName+"_"+ item.ownerMobile+"_"+ item.carNo+'" /> ' + item.ownerName+ " " + item.ownerMobile+ " " + item.carNo+"</label>";
				linkManHtmlArr.push(linkManHtml
					.replaceAll("{radio}",' <input type="radio" name="linkman" value="'+item.id+"_"+ item.ownerName+"_"+ item.ownerMobile+"_"+ item.carNo+'" /> ')
					.replaceAll("{name}",item.ownerName)
					.replaceAll("{mobile}",item.ownerMobile)
					.replaceAll("{car}", item.carNo) 
				);
			}); 
		} else { 
		}
	},{});
}
listCar();
window.checkedRadio = function(obj){
	$(obj).find("input")[0].checked = true;
}
window.openLink = function(){  
	
	layer.open({//页面层
	  title:['常用联系人', 'text-align: center'],
	  type: 1,
	  skin: 'layui-layer-rim', //加上边框 
	  area: ['420px', '340px'], //宽高   
	  content: '<table style="width:100%;cursor: pointer;"><tr align="left"><td></td><td>联系人</td><td>手机号</td><td>车牌号</td></tr>'+linkManHtmlArr.join('')+'</table>',
	  btn: ['选好了', '关闭'] //只是为了演示
	  ,yes: function(){
		  var links = $("input[name=linkman]:checked(true)");  
		  if(links && links.length == 1){ 
			  links = $("input[name=linkman]:checked(true)").attr("value");
			  linkManShow(links.split("_")[0],links.split("_")[1],links.split("_")[2],links.split("_")[3]);
			  layer.closeAll();   
		  } else {
			    layer.msg("请选择联系人");
		  }
	  }
	  ,btn2: function(){
	    layer.closeAll();
	  }
	}); 
}

// 优惠券下拉列表 
function listCoupon(serveId,len){
	
	BaseUtil.get("eb/coupon/getCouponByServeId",function(result){
		var coupon = document.getElementById("coupon");
		if(result.length > 0){ 
			var li = "<option value='{couponid}'>{couponname}</option>";
			var html = [];  
			$.each(result,function(idx,item){
				html.push(li.replaceAll("{couponname}", item.couponTypeName).replaceAll("{couponid}",item.id+"_"+item.price));
			});    
			$("#coupon").append(html.join(''));    
			coupon.disabled= false;
			coupon.style.color = '#f98322';  
			document.getElementById("coupon").style.borderColor = '#f98322';   
		} else {
			if(len == 0){
				li = '<option selected value="">没有可用优惠券</option>';  
				$("#coupon").html(li);     
				coupon.disabled= true;  
				coupon.style.color = 'gray';  
				coupon.style.borderColor = 'gray';   
			}
		}
	},{'serveId':serveId});       
}; 
// 洗车卡列表 
function listWashCard(serveId,estateId,serviceValue){  
	
	$("#coupon").html('<option selected value="">选择可用优惠券</option>'); 
	BaseUtil.get("eb/washCard/listWashCard",function(result){
		var wash = document.getElementById("washcard")
		if(result.length > 0){ 
			var li = "<option value='{couponid}'>{couponname}</option>";
			var html = [];  
			$.each(result,function(idx,item){
				html.push(li.replaceAll("{couponname}", item.cardTypeName).replaceAll("{couponid}",item.id+"_" + -1));
			});    
			$("#coupon").append(html.join(''));     
			coupon.disabled= false;
			coupon.style.color = '#f98322';  
			document.getElementById("coupon").style.borderColor = '#f98322';   
		} 
		listCoupon(serveId,result.length); 
	},{'serveId':serveId,'estateId':estateId,'serveStandardType':serviceValue});     
}; 

});
require.sync(['DateUtil','jedate']);
//选择日期初始化 jeDate.skin(''); 
$("#dateinfo").val(DateUtil.getDate());
 jeDate({
	dateCell:"#dateinfo",
	isinitVal:true,   
	isTime:true,   
	minDate:DateUtil.getDate(),//"2014-09-19",  
	//maxDate:DateUtil.addCountDate(30),//"2099-12-31", //最大日期
	okfun:function(val){ 
		listBespeaktime($('#dateinfo').val())
	} ,
 	choosefun:function(val) {
		listBespeaktime($('#dateinfo').val()) 
 	},
	clearfun:function(val) {
		listBespeaktime($('#dateinfo').val())
	}
	/*
	dateCell:"#dateval",
	format:"YYYY-MM-DD", //日期格式
	minDate:"1900-01-01", //最小日期
	maxDate:"2099-12-31", //最大日期
	isinitVal:false, //是否初始化时间
	isTime:false, //是否开启时间选择
	isClear:true, //是否显示清空
	festival:false, //是否显示节日
	zIndex:999,  //弹出层的层级高度
	*/
	//alert("YYYY/MM".match(/\w+|d+/g).join("-"))
 });   
